<template>
	<jk-dialog
		v-model="showDialog"
		:title="`${dataId ? '编辑' : '新增'}-班次档案`"
		width="500px"
		:show-content-loading="showLoading"
		:confirm-btn-loading="saveBtnLoading"
		@on-cancel="onVisibleChange(false)"
		@on-visible-change="onVisibleChange"
		@on-confirm="onConfirmBtn"
	>
		<el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="110px" :show-message="false">
			<el-row>
				<el-col :span="22">
					<el-form-item class="margin-bottom-10" label="班制类别" prop="typeId">
						<el-select v-model="ruleForm.typeId" class="width-100-percent" placeholder="班制类别">
							<el-option
								v-for="item in scheduleList"
								:key="item.id"
								:label="item.name"
								:value="item.id"
							></el-option>
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="22">
					<el-form-item class="margin-bottom-10" label="区域" prop="workshopId">
						<el-select v-model="ruleForm.workshopId" class="width-100-percent" placeholder="区域">
							<el-option
								v-for="item in workshopList"
								:key="item.id"
								:label="item.name"
								:value="item.id"
							></el-option>
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="22">
					<el-form-item class="margin-bottom-10" label="编号" prop="code">
						<el-input v-model="ruleForm.code" placeholder="编号" />
					</el-form-item>
				</el-col>
				<el-col :span="22">
					<el-form-item class="margin-bottom-10" label="名称" prop="name">
						<el-input v-model="ruleForm.name" placeholder="名称" />
					</el-form-item>
				</el-col>
				<el-col :span="22">
					<el-form-item label="开始时间" prop="beginHour" class="margin-bottom-10 ">
						<el-time-select
							v-model="ruleForm.beginHour"
							:picker-options="{
								start: '00:00',
								step: '00:05',
								end: '24:00'
							}"
							style="width: 100%;"
							value-format="HH:mm"
							placeholder="开始时间"
							@change="getBeginHour"
						/>
					</el-form-item>
				</el-col>
				<el-col :span="22">
					<el-form-item label="结束时间" prop="endHour" class="margin-bottom-10 ">
						<el-time-select
							v-model="ruleForm.endHour"
							:picker-options="{
								start: '00:00',
								step: '00:05',
								end: '24:00'
							}"
							style="width: 100%;"
							value-format="HH:mm"
							placeholder="结束时间"
							@change="getEndHour"
						/>
					</el-form-item>
				</el-col>
				<el-col :span="22">
					<el-form-item class="margin-bottom-10" label="工时">
						<span class="read-only-2">{{ ruleForm.workingHours }}</span>
					</el-form-item>
				</el-col>
				<el-col :span="22">
					<el-form-item class="margin-bottom-10" label="单日夜班补贴" prop="singleDayNightShiftSubsidy">
						<jk-number-input v-model="ruleForm.singleDayNightShiftSubsidy" placeholder="单日夜班补贴" />
					</el-form-item>
				</el-col>
				<el-col :span="22">
					<el-form-item class="margin-bottom-10" label="排序">
						<jk-number-input v-model="ruleForm.sortNum" placeholder="排序" />
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
	</jk-dialog>
</template>

<script>
    import calHeight from '/src/mixins/cal-table-height';
    import {
        workforcemanagementShiftCreate,
        workforcemanagementShiftUpdate,
        workforcemanagementShiftGet
    } from '../../../api/schedule/shift';
    import { systemBusinessDictPage } from '../../../api/basicData/businessDict';
    import { mathJsAdd } from '../../../utils/jk/jk-cals';
    export default {
        props: {
            dialogState: {
                type: Boolean,
                default: false
            },
            dataId: {
                type: [String, Number],
                default: ''
            }
        },
        mixins: [calHeight],
        data() {
            return {
                scheduleList: [],
                workshopList: [],
                showDialog: false,
                showLoading: true,
                saveBtnLoading: false,
                ruleForm: {
                    id: null,
                    code: '',
                    name: '',
                    workshopId: '',
                    beginHour: '',
                    endHour: '',
                    sortNum: 1,
                    workingHours: '',
                    typeId: null,
                    singleDayNightShiftSubsidy: 0
                },
                rules: {
                    code: [{ required: true, trigger: 'change' }],
                    name: [{ required: true, trigger: 'change' }],
                    beginHour: [{ required: true, trigger: 'change' }],
                    endHour: [{ required: true, trigger: 'change' }],
                    workshopId: [{ required: true, trigger: 'change' }],
                    typeId: [{ required: true, trigger: 'change' }]
                }
            };
        },
        methods: {
            getWorkingHour(endTime, beginTime) {
                let data = null;
                if (endTime.split(':')[0] > beginTime.split(':')[0]) {
                    // 结束的小时大于(>)开始的小时
                    if (endTime.split(':')[1] >= beginTime.split(':')[1]) {
                        data = (Number(endTime.split(':')[0]) - Number(beginTime.split(':')[0])) + ':' + (Number(endTime.split(':')[1]) - Number(beginTime.split(':')[1]));
                    } else {
                        data = (Number(endTime.split(':')[0]) - Number(beginTime.split(':')[0]) - 1) + ':' + (Number(endTime.split(':')[1]) + 60 - Number(beginTime.split(':')[1]));
                    }
                } else if (endTime.split(':')[0] < beginTime.split(':')[0]) {
                    // 结束的小时小于（<）开始的小时
                    if (endTime.split(':')[1] >= beginTime.split(':')[1]) {
                        data = (Number(endTime.split(':')[0]) + 24 - Number(beginTime.split(':')[0])) + ':' + (Number(endTime.split(':')[1]) - Number(beginTime.split(':')[1]));
                    } else {
                        data = (Number(endTime.split(':')[0]) + 24 - Number(beginTime.split(':')[0]) - 1) + ':' + (Number(endTime.split(':')[1]) + 60 - Number(beginTime.split(':')[1]));
                    }
                } else if (endTime.split(':')[0] === beginTime.split(':')[0]) {
                    // 结束的小时等于(=)开始的小时
                    if (endTime.split(':')[1] >= beginTime.split(':')[1]) {
                        data = (Number(endTime.split(':')[0]) - Number(beginTime.split(':')[0])) + ':' + (Number(endTime.split(':')[1]) - Number(beginTime.split(':')[1]));
                    } else {
                        data = '23' + ':' + (Number(endTime.split(':')[1]) + 60 - Number(beginTime.split(':')[1]));
                    }
                }
                const hour = data.split(':')[0] < 10 ? '0' + data.split(':')[0] : data.split(':')[0];
                const min = data.split(':')[1] < 10 ? '0' + data.split(':')[1] : data.split(':')[1];
                return mathJsAdd(parseInt(hour), parseInt((min / 60) * 10) / 10);
            },
            getBeginHour(value) {
                if (value && this.ruleForm.endHour) {
                    this.ruleForm.workingHours = this.getWorkingHour(this.ruleForm.endHour, value);
                } else {
                    this.ruleForm.workingHours = null;
                }
            },
            getEndHour(value) {
                if (value && this.ruleForm.beginHour) {
                    this.ruleForm.workingHours = this.getWorkingHour(value, this.ruleForm.beginHour);
                } else {
                    this.ruleForm.workingHours = null;
                }
            },
            getParamData() {
                const params = JSON.parse(JSON.stringify(this.ruleForm));
                if (!this.dataId) delete params.id;
                const typeItem = this.scheduleList.find((x) => x.id === params.typeId) || {};
                params.typeCode = typeItem.code;
                params.typeName = typeItem.name;
                const workshopItem = this.workshopList.find((x) => x.id === params.workshopId) || {};
                params.workshopCode = workshopItem.code;
                params.workshopName = workshopItem.name;
                return params;
            },
            createAndUpdateRequest() {
                this.saveBtnLoading = true;
                const api = !this.dataId ? workforcemanagementShiftCreate : workforcemanagementShiftUpdate;
                api(this.getParamData()).then(res => {
                    this.saveBtnLoading = false;
                    if (res.data.status === 200) {
                        this.$tipsBar(this, 'save');
                        this.$emit('on-finish');
                    }
                });
            },
            onConfirmBtn() {
                this.$refs['ruleForm'].validate(valid => {
                    if (valid) {
                        this.createAndUpdateRequest();
                    } else {
                        this.$tipsBar(this, 'validator');
                    }
                });
            },
            onVisibleChange(e) {
                this.$emit('on-visible-change', e);
                if (!e) {
                    Object.assign(this.$data, this.$options.data());
                    this.$nextTick(() => {
                        this.$refs.ruleForm.resetFields();
                    });
                }
            },
            getDetailRequest() {
                return workforcemanagementShiftGet({ id: this.dataId }).then(res => {
                    if (res.data.status === 200) {
                        this.ruleForm = res.data.res;
                    }
                });
            },
            getScheduleCategoryListRequest() {
                return systemBusinessDictPage({ categoryCode: 'SCHEDULE_CATEGORY' }).then(res => {
                    if (res.data.status === 200) {
                        this.scheduleList = res.data.res;
                    }
                });
            },
            async getDependentData() {
                this.showLoading = true;
                this.workshopList = this.$store.state.user.userWorkshop.workshopList;
                await this.getScheduleCategoryListRequest();
                if (this.dataId) await this.getDetailRequest();
                this.showLoading = false;
            }
        },
        watch: {
            dialogState(newVal) {
                this.showDialog = newVal;
                if (newVal) {
                    this.getDependentData();
                }
            }
        }
    };
</script>
